import { Router } from 'express'
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { User } from '../models/User.js'
import { auth } from '../middleware/auth.js'

const router = Router()

router.post('/login', async (req, res, next) => {
  try {
    const { username, password } = req.body || {}
    const u = await User.findByUsername(username)
    if (!u) return res.status(401).json({ code: 401, message: '用户名或密码错误' })

    // ⚠️ 临时简化：直接比较明文密码（仅用于开发测试）
    // 生产环境应使用: bcrypt.compareSync(password || '', u.password_hash)
    if (password !== u.password_hash) {
      return res.status(401).json({ code: 401, message: '用户名或密码错误' })
    }
    const token = jwt.sign(
      { id: u.id, role: u.role, name: u.name },
      process.env.JWT_SECRET || 'dev_secret',
      { expiresIn: '2h' },
    )
    res.json({
      code: 0,
      message: 'ok',
      data: { token, role: u.role, user: { id: u.id, name: u.name, username: u.username } },
    })
  } catch (error) {
    next(error)
  }
})

router.get('/me', auth, async (req, res, next) => {
  try {
    const u = await User.findById(req.user.id)
    if (!u) return res.status(401).json({ code: 401, message: 'Unauthorized' })
    res.json({
      code: 0,
      message: 'ok',
      data: { user: { id: u.id, name: u.name, username: u.username }, role: u.role },
    })
  } catch (error) {
    next(error)
  }
})

export default router
